package com.libbase.datarepository

class DataRepositoryManager private constructor() {
    companion object {
        val instance: DataRepositoryManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            DataRepositoryManager()
        }
    }

    private val repositories: MutableMap<String, DataRepositoryInterface> = mutableMapOf()

    private val repositoryBuilders: MutableMap<String, DataRepositoryInterface.Builder> = mutableMapOf()

    var repositoryDataCallback: ((id: String, encodeData: Any?) -> Unit)? = null

    var repositoryItemCallBack: ((id: String, encodeItem: Any?) -> Unit)? = null

    fun register(builder: DataRepositoryInterface.Builder) {
        repositoryBuilders[builder.id] = builder
    }

    fun repository(id: String): DataRepositoryInterface? {
        var repository: DataRepositoryInterface? = repositories[id]
        if (repository != null) {
            return repository
        }

        repository = repositoryBuilders[id]?.build()
        if (repository != null) {
            repository.dataChangeCallBack = { value ->
                repositoryDataCallback?.let { it(id, value) }
            }

            repository.itemChangeCallBack = { value ->
                repositoryItemCallBack?.let { it(id, value) }
            }

            repositories[id] = repository
        }

        return repository
    }
}